var admin = require('./admin');
var encrypt = require('../util/encrypt');

module.exports = function(app){
    app.all('/login',doPost);
    app.get('/', doLogin);
    app.all('/cmdTest', admin.test);// 这是给编码工具用的

    app.post('/', checkLogin);
    app.post('/', doPost);
}

function doLogin(req, res){
    res.render('index');
}
function doPost(req, res){
    var cmd = req.body.cmd;
    if(!cmd){
        res.send(404);
        logger.error("前端发送参数错误。");
        return;
    }
    route(cmd,req, res);
};

// 真实路由过程，动态加载service
function route(cmd,req, res){
    // cmd like: Y2hhdDpbMSwyLCJ3Iix7YToxfV0= 解密后：chat:[1,2,"w",{a:1}]
    var query = encrypt.utf8to16(encrypt.base64decode(cmd));
    var index = query.indexOf(settings.splitFlag);
    cmd = query;
    var args = null;

    if(-1 != index){// 表示命令后面带有参数
        cmd = query.substr(0,index);
        args = query.substr(index+1);
        args = eval("("+args+")");
    }

    try{
        var service = require('../services/'+cmd);
        service.main(args,req,res);
    } catch (e) {
        logger.info(e);
        res.send(404);
    }
}

// 检测是否登录
function checkLogin(req,res,next){
    if(!req.session.user){
        res.render('index');
        return;
    }
    next();
}